import { queryCurrent, query as queryUsers } from '@/services/user';
import { history } from 'umi';
import { groupBy } from '@/utils/utils'
const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
  },
  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      yield put({
        type: 'save',
        payload: response,
      });
    },

    *fetchCurrent(_, { call, put }) {
      const token = localStorage ? localStorage.getItem('token') : ''
      if(!token) {
        history.replace('/user/login')
        return
      }
      const response = yield call(queryCurrent);
      const { url_list, username, region } = response
      const groupUrlList = groupBy(url_list, 'url')
      const _urlList = groupUrlList.map(item => {
        return {
          url: item[0].url,
          modules: item
        }
      })

      yield put({
        type: 'saveCurrentUser',
        payload: {username, url_list: _urlList, ...region},
      });
    },
  },
  reducers: {
    saveCurrentUser(state, action) {
      return { ...state, currentUser: action.payload || {} };
    },

    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
export default UserModel;
